open(BUFF,"../common/WR_BRCA_normalized_450_methylation_tumor_normal_only.txt");
$line=<BUFF>;
#print $line."\n";
@samples=split("\t",$line);
for($i=0;$i<@samples;$i++)
{
	@temp=split("-",$samples[$i]);
	#die "$temp[0]-$temp[1]-$temp[2]\n";
	$hsh{"$temp[0]-$temp[1]-$temp[2]"}=1;
}
$ls =`ls ./level3/`;
undef(@samples);
@ls=split("\n",$ls);
for($i=0;$i<@ls;$i++)
{
	@temp=split("__",$ls[$i]);
	@samp=split('-',$temp[2]);
	$samp[3] =~ s/A//g;
    	$samp[3] =~ s/B//g;
	#print "$temp[2]\n";
	#die "$samp[3]\n";
	if($samp[3] eq "01" || $samp[3] eq "11")
	{	
		if(exists($hash{"$samp[0]-$samp[1]-$samp[2]"}) && $samp[3] ne $temp{"$samp[0]-$samp[1]-$samp[2]"})
		{
			$hash{"$samp[0]-$samp[1]-$samp[2]"}=2;
		}
		else
		{
			$hash{"$samp[0]-$samp[1]-$samp[2]"}=1;
			$temp{"$samp[0]-$samp[1]-$samp[2]"}=$samp[3];
		}
	}
}
open(WRBUFF,">selected.txt") or die "no file selected.txt\n";
print WRBUFF "ID\tchrom\tloc.start\tloc.end\tnum.mark\tseg.mean\n";
for($i=0;$i<@ls;$i++)
{
	@temp=split("__",$ls[$i]);
        @samp=split('-',$temp[2]);
	$samp[3] =~ s/A//g;
	$samp[3] =~ s/B//g;
	if($hsh{"$samp[0]-$samp[1]-$samp[2]"} ==1 &&($hash{"$samp[0]-$samp[1]-$samp[2]"} ==2)  && ($samp[3] eq "01" || $samp[3] eq "11") && !exists($tmp{"$samp[0]-$samp[1]-$samp[2]-$samp[3]"}))
	{
		$tmp{"$samp[0]-$samp[1]-$samp[2]-$samp[3]"}=1;
		open(BUFF,"./level3/$ls[$i]") or die "no file ./level3/$ls[$i] exists\n";
		$line=<BUFF>;
		while(<BUFF>)
		{
			print WRBUFF $_;
		}
		#system("cp ./level3/$ls[$i] ./selected/");
		#print "$temp[2]\n";
	}
}
